package controller

import (
	"admin/contrib/session"
	"admin/model"
	"common/helper"
	"encoding/json"
	"github.com/valyala/fasthttp"
)

type ChannelConfigController struct{}

// ConfigInsert 代理渠道配置新增
func (that *ChannelConfigController) ConfigInsert(ctx *fasthttp.RequestCtx) {

	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	admin := session.AdminGet(ctx)

	err = model.ChannelConfigInsert(admin["name"], admin["id"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "succeed")
}

// ConfigUpdate 代理渠道配置更新
func (that ChannelConfigController) ConfigUpdate(ctx *fasthttp.RequestCtx) {

	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	admin := session.AdminGet(ctx)

	err = model.ChannelConfigUpdate(admin["name"], admin["id"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

// ApifeeUpdate 代理渠道api费率更新
func (that ChannelConfigController) ApifeeUpdate(ctx *fasthttp.RequestCtx) {

	param := model.TblOperatorInfo{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	admin := session.AdminGet(ctx)

	newFeeRate := []model.ApiFee{}
	json.Unmarshal([]byte(param.ApiFee), &newFeeRate)
	apiFeeRate := map[string]float64{}
	for _, v := range newFeeRate {
		apiFeeRate[v.GameId] = v.Rate

	}
	jsonBytes, _ := json.Marshal(apiFeeRate)
	param.ApiFee = string(jsonBytes)
	err = model.ChannelApifeeUpdate(admin["name"], admin["id"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}
